package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-06-04
 * Time: 17:11
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 编程式事务
    @Autowired
    private DataSourceTransactionManager transactionManager; // 事务管理器

    @Autowired
    private TransactionDefinition transactionDefinition; // 定义事务属性

    @RequestMapping("/del")
    public int del(Integer id) {

        if (id == null || id <= 0) return 0;

        TransactionStatus transactionStatus = null;
        int result = 0;

        try {

            // 1. 开启事务
            // 传入 transactionDefinition 给事务管理器 transactionManager 创建一个 transactionStatus 事务
            transactionStatus = transactionManager.getTransaction(transactionDefinition);

            result = userService.del(id);
            System.out.println("删除 : " + result + " 条数据");
            String a = null;
            int b = 10 / 0;
            // 2. 事务提交
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            // 事务对象正常
            if (transactionStatus != null) {
                transactionManager.rollback(transactionStatus); // 事务回滚
            }
            return 0;
        }
        return result;
    }
}
